package part21;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * @author wcj
 * @Date 2021/6/7 17:10
 * @Version 1.0
 */
public class Part218 implements Runnable {


    @Override
    public void run() {
        try {
            while (true) {
                TimeUnit.MILLISECONDS.sleep(100);
                System.out.println(Thread.currentThread() + ":" + this);
            }
        } catch (InterruptedException e) {
            System.out.println("Interrupt");
        }
    }

    /**
     * 线程池的参数之一为ThreadFactory:可以实现ThreadFactory
     *
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        ExecutorService exec = Executors.newCachedThreadPool(new DaemonThreadFactory());
        for (int i = 0; i < 5; i++) {
            exec.execute(new Part218());
        }
        System.out.println("All Daemons started");
        TimeUnit.MILLISECONDS.sleep(500);
    }
}

class DaemonThreadFactory implements ThreadFactory {
    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r);
        thread.setDaemon(true);
        return thread;
    }
}
